//
//  XS_VIPVC.swift
//  XueDao
//
//  Created by Mac on 2020/12/18.
//

import UIKit
import SwiftyStoreKit

class XS_VIPCourseM : XS_BaseModel{
    var records: [XS_VIPCourseModel] = []
    var total = 0
    var size = 10 // 默认页数
    var current = 0
    var searchCount = false
    var pages = 0
}

class XS_VIPCourseModel: XS_BaseModel {
//    "id": 106,
//                    "curriculumName": "特种兵介绍课",
//                    "introduce": "简单介绍一下特种兵",
//                    "purchaseNum": 0,
//                    "curriculumImgUrl": "http://xuedaozaixain.oss-cn-beijing.aliyuncs.com/system/202012/dBHfaS_1609133878393.png",
//                    "curriculumNum": 1,
//                    "price": 0.00
    var id = ""
    var curriculumName = ""
    var introduce = ""
    var purchaseNum = ""
    var curriculumImgUrl = ""
    var curriculumNum = ""
    var curriculumType = ""
    var price = ""
    
    var vipIsFree = ""
    var isFree = ""
    var vipPrice = ""
    var discountPrice = ""
}

class XS_VIPVC: XS_BaseVC {

    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var iconImageView: UIImageView!
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var contentLabel: UILabel!
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var openBtn: UIButton!
    @IBOutlet weak var openView: UIImageView!
    
    @IBOutlet weak var timeLabel: UILabel!
    @IBOutlet weak var logBtn: QMUIButton!
    @IBOutlet weak var operateBtn: UIButton!
    
    @IBOutlet weak var priceLabel: UILabel!
    @IBOutlet weak var dayPriceLabel: UILabel!
    
    @IBOutlet weak var contentImgV: UIImageView!
    
    var dataModel = XS_VIPCourseM()
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        title = "开通VIP"
        shouldNavBarHidden = true
        isStatusBarBlack = false
        loadCustomBar()
        scrollView.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: .bottomHeight, right: 0)
        collectionView.register(UINib.init(nibName: "XS_VIPCourseItemCell", bundle: Bundle.main), forCellWithReuseIdentifier: "XS_VIPCourseItemCell")
        requestData()
        requestCourseData(true)
        
        logBtn.imagePosition = .right
        logBtn.spacingBetweenImageAndTitle = 0
        collectionView.isScrollEnabled = false
    }
    
    @objc func integralRuleAction(){
        let point = CGPoint(x: .screenWidth/2.0, y: .screenHeight/2.0 - .scale*150)
        view.isUserInteractionEnabled = false
        view.makeToastActivity(point)
        SwiftyStoreKit.restorePurchases { (result) in
            if result.restoredPurchases.count != 0{
                let purchase = result.restoredPurchases.first!
                if purchase.needsFinishTransaction{
                    SwiftyStoreKit.finishTransaction(purchase.transaction)
                }
                let receiptData = SwiftyStoreKit.localReceiptData
                let receiptString = receiptData?.base64EncodedString(options: [])
                _ = CGPoint(x: .screenWidth/2.0, y: .screenHeight/2.0 - .scale*150)
                XS_NetWork.requestJson("/vip/openVipByIOS", parameters: ["transactionId":purchase.transaction.transactionIdentifier ?? "","payload":receiptString!])
                    .subscribe(onNext: { resp in //直接返回原始数据 resp.data
                        self.view.isUserInteractionEnabled = true
                        self.view.hideToastActivity()
                        if resp.success{
                            let infoModel = XS_Singleton.shared.infoModel
                            infoModel?.userBO.userType = "vip"
                            XS_Singleton.shared.infoModel = infoModel
                            self.requestData()
                        }else{
                            self.view.makeToast(resp.msg)
                        }
                    })
            }else{
                self.view.isUserInteractionEnabled = true
                self.view.hideToastActivity()
                self.view.makeToast("恢复购买失败")
            }
        }
    }
    
    lazy var ruleBtn : UIButton = {
        let ruleBtn = UIButton.init(frame: CGRect.init(x: .screenWidth - 90, y: .barHeight, width: 80, height: 44))
        ruleBtn.setTitle("恢复购买", for: .normal)
        ruleBtn.setTitleColor(.white, for: .normal)
        ruleBtn.titleLabel?.font = .systemFont(ofSize: 15)
        ruleBtn.addTarget(self, action: #selector(integralRuleAction), for: .touchUpInside)
        return ruleBtn
    }()
    
    func requestCourseData(_ isFirst: Bool = false){
        if isFirst {
            dataModel.current = 0
            dataModel.records.removeAll()
        }
        XS_NetWork.requestJson("/curriculum/queryVipCurriculum", parameters: ["pageNo" : dataModel.current+1, "pageSize" : 4/*dataModel.size*/])
            .mapModel(type: XS_VIPCourseM.self) // 返回 模型数组 和原始数据
            .subscribe(onNext: { [weak self] model, resp in
                guard let `self` = self, resp.success, let model = model else { return }
                model.records = self.dataModel.records + model.records
                self.dataModel = model
                self.collectionView.reloadData()
            }).disposed(by: disposeBag)
    }


    func requestData(){
        //详细信息
        XS_NetWork.requestJson("/vip/getUserVipInfo")
            .mapModel(type: XS_VIPDetailModel.self) // 返回 模型对象 和原始数据
            .subscribe(onNext: { model, resp in
                self.iconImageView.sd_setImage(with: URL.init(string: model?.userInfo?.userImgSrc ?? ""), completed: nil)
                self.nameLabel.text = model?.userInfo?.username
                self.contentImgV.sd_setImage(with: URL.init(string: model?.vipInfo?.introducePic ?? ""), completed: nil)
                self.openBtn.isHidden = model?.userInfo?.userType != "user"
                self.priceLabel.text = "￥" + "\(model?.vipInfo?.money ?? 198)"
                self.dayPriceLabel.text = "每日仅需 " + (model?.vipInfo?.moneyDay ?? "0.5") + " 元"
                //判断显示隐藏
                if self.openBtn.isHidden {
                    self.openBtn.snp.updateConstraints { (make) in
                        make.height.equalTo(0)
                    }
                    self.ruleBtn.removeFromSuperview()
                    //是会员
                    self.timeLabel.text = (model?.userInfo?.vipExpirationTime ?? "")+"到期"
                    self.timeLabel.isHidden = true
                    self.logBtn.isHidden = false
                    let vipExpirationTime = model?.userInfo?.vipExpirationTime ?? ""
                    let dateFormater = DateFormatter.init()
                    dateFormater.dateFormat = "yyyy-MM-dd HH:mm:ss"
                    let vipExpirationDate = dateFormater.date(from: vipExpirationTime)
                    let monthDate = Date.init(timeIntervalSinceNow: 30 * 24 * 3600)
                    let compareResult = monthDate.compare(vipExpirationDate ?? Date.init())
                    if compareResult == .orderedDescending {
                        //到期小于一个月
                        self.operateBtn.isHidden = false
                        self.operateBtn.setTitle("会员续费", for: .normal)
                    }else{
                        self.operateBtn.isHidden = true
                    }
                    self.priceLabel.isHidden = true
                    self.contentLabel.text = model?.userInfo?.vipExpirationTime ?? ""
                } else {
                    self.openBtn.snp.updateConstraints { (make) in
                        make.height.equalTo(48)
                    }
                    self.contentLabel.text = "当前未购买VIP"
                    self.view.addSubview(self.ruleBtn)
                    self.priceLabel.isHidden = false
                    self.operateBtn.isHidden = false
                    self.operateBtn.setTitle("立即开通", for: .normal)
                    self.logBtn.isHidden = true
                }
                
            }).disposed(by: disposeBag)
    }
    @IBAction @objc func openBtnAction(_ sender: UIButton) {
        let point = CGPoint(x: .screenWidth/2.0, y: .screenHeight/2.0 - .scale*150)
        view.isUserInteractionEnabled = false
        view.makeToastActivity(point)
        SwiftyStoreKit.purchaseProduct("com.xuedao.xuedaoonlineYearVIP") { (result) in
            
            switch result {
            case .success (let purchase):
                if purchase.needsFinishTransaction{
                    SwiftyStoreKit.finishTransaction(purchase.transaction)
                }
                let receiptData = SwiftyStoreKit.localReceiptData
                let receiptString = receiptData?.base64EncodedString(options: [])
                _ = CGPoint(x: .screenWidth/2.0, y: .screenHeight/2.0 - .scale*150)
                XS_NetWork.requestJson("/vip/openVipByIOS", parameters: ["transactionId":purchase.transaction.transactionIdentifier ?? "","payload":receiptString!])
                    .subscribe(onNext: { resp in //直接返回原始数据 resp.data
                        self.view.isUserInteractionEnabled = true
                        self.view.hideToastActivity()
                        if resp.success{
                            let infoModel = XS_Singleton.shared.infoModel
                            infoModel?.userBO.userType = "vip"
                            XS_Singleton.shared.infoModel = infoModel
                            self.requestData()
                        }else{
                            self.view.makeToast(resp.msg)
                        }
                    })
            case .error (let error):
                self.view.isUserInteractionEnabled = true
                self.view.hideToastActivity()
                self.view.makeToast(error.localizedDescription)
                break
            }
        }
    }
    
    @IBAction func logBtnAction(_ sender: QMUIButton) {
        let logVC = XS_VIPLogVC()
        navigationController?.pushViewController(logVC, animated: true)
    }
}

extension XS_VIPVC : UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataModel.records.count > 4 ? 4 : dataModel.records.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "XS_VIPCourseItemCell", for: indexPath) as! XS_VIPCourseItemCell
        if indexPath.item < dataModel.records.count {
            cell.model = dataModel.records[indexPath.item]
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize.init(width: floor((.screenWidth - 45) / 2), height: 196)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets.init(top: 15, left: 15, bottom: 15, right: 15)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 15
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 15
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        return CGSize(width: (.screenWidth - 30), height: 1)
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let type = dataModel.records[indexPath.item].curriculumType
        let id = dataModel.records[indexPath.item].id
        if type == "seriesCurriculum" || type == "notSeriesCurriculum" {
            //线上课
            let vc = XS_KeChengVC()
            vc.id = id
            navigationController?.pushViewController(vc, animated: true)
        }else if type == "offlineCurriculum"{
            //线下课
            let vc = XS_KCXianxiaVC()
            vc.id = id
            navigationController?.pushViewController(vc, animated: true)
        }else if type == "live"{
            //直播课
            let vc = XS_KCZhiboVC()
            vc.id = id
            navigationController?.pushViewController(vc, animated: true)
        }
    }
}
